#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
  STDataType* a;
  int top;//栈顶
  int capacity;//容量

}Stack;

//初始化函数
void StackInit(Stack* pst)
{
  pst->a = (STDataType*)malloc(sizeof(STDataType)*4);
  pst->top = 0;
  pst->capacity = 4;
}
//销毁栈
void StackDestory(Stack* pst)
{
 assert(pst);
 free(pst->a);
 pst->a = NULL;
 pst->top = 0;
 pst->capacity = 0;
}
//入栈
void StackPush(Stack* pst,STDataType x)
{
  assert(pst);
  if(pst->top==pst->capacity)
  {
    STDataType* tmp = (STDataType*)realloc(pst->a,sizeof(STDataType)*(pst->capacity)*2);
    if(tmp==NULL)
    {
      printf("realloc fail\n");
      exit(-1);
    }
    printf("增容成功！！！\n");
    pst->a = tmp;
    pst->capacity *=2;
  }
  pst->a[pst->top] = x;
  pst->top++;
}
//判断栈是否空
bool StackEmpty(Stack* pst)
{
  assert(pst);
  return pst->top==0;
}
//出栈
void StackPop(Stack* pst)
{
  assert(pst);
  assert(!StackEmpty(pst));
  pst->top--;
}

//获取栈顶元素
STDataType StackTop(Stack* pst)
{
  assert(pst);
  assert(!StackEmpty(pst));
  return pst->a[pst->top-1];
}

//获取有效元素个数
int StackSize(Stack* pst)
{
  assert(pst);
  return pst->top;
}

//top代表有效元素的下一个位置
int main()
{
  Stack st;
  StackInit(&st);
  int i=0;
  StackPush(&st,1);
  StackPush(&st,2);
  StackPush(&st,3);
  StackPush(&st,4);
//  StackPush(&st,5);
  
  int size=StackSize(&st);
  for(i=0;i<size;i++)
  {
    printf("%d  ",StackTop(&st));
    StackPop(&st);
  }

  return 0;
}
